import {reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogout} from '@/api'

import {setToken,getToken,removeToken} from '@/utils/token'

const state = {
    codeData:"",
    // token:'',
    token: getToken(), //刷新之后token的值从本地存储获得
    userInfo:{}
}
const mutations = {
    GETCODE(state,codedata){
        
        state.codeData = codedata 
    },
    USERLOGIN(state,userlogindata){
        state.token = userlogindata 
    },
    GETUSERINFO(state,userdata){
        state.userInfo  = userdata

    },
    CLEAR(state){
        state.token = '', //仓库里的清空
        state.userInfo = {},
        removeToken// 本地也清空

    }
}
const actions = {
    // 获取验证码
    async getCodeData({commit},phone){
        let result = await reqGetCode(phone);
        if(result.code == 200){
            commit('GETCODE',result.data)
            // return 'ok'
        }
    },
    // 用户注册
    async userRegister({commit},user){
        let result = await reqUserRegister(user);
        if(result.code == 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 用户登录
    async userLogin({commit},user){
        let result = await reqUserLogin(user);
        if(result.code == 200){
            commit('USERLOGIN',result.data.token) //给仓库里的token赋值
            //持久化存储token,存到本地
            setToken(result.data.token);
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        let result = await reqUserInfo();
        if(result.code == 200){
            commit('GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 退出登录,通知服务器清除token，并将本地的也清除掉
    async userLogout({commit}){
        let result = await reqLogout();
        if(result.code == 200){
            // action 不能操作state
            commit('CLEAR')
            return 'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },


    
}
const getters = {}

export default {
    namespaced: true, //命名空间是防止仓库中出现同名的情况
    state,
    mutations,
    actions,
    getters,
  }